<template>
  <div class="swiper-container" :style="{height:imagesHeight[currentImage] + 'rpx'}">
    <img :src="imagesUrl[0]" @load="preFirstImage" @error="errorImageFirst" class="hide">
    <swiper :style="{height:imagesHeight[currentImage] + 'rpx'}" @change="swiperChange">
      <div v-for="(item,i) in imagesUrl" :key="item">
        <swiper-item>
          <img :src="item" @load="loadImage($event,i)" @error="errorImage($event,i)" />
        </swiper-item>
      </div>
    </swiper>
    <div class="indicator-block text-white fs-sm px-4">
      {{currentImage + 1}}<span class="px-2">/</span>{{imagesUrl.length}}
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      imagesUrl: [
        'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=600',
        'xxxx',
        'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
      ],
      currentImage: 0,
      imagesHeight: [],
      // 默认图片(防裂)
      defaultImage: {
        url: 'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=620',
        height: 440
      }
    }
  },
  methods: {
    swiperChange(e) {
      this.currentImage = e.mp.detail.current
    },
    loadImage(e, i) {
      this.$set(this.imagesHeight, i, e.mp.detail.height)
    },
    errorImage(e, i) {
      const { url, height } = this.defaultImage
      this.$set(this.imagesUrl, i, url)
      this.$set(this.imagesHeight, i, height)
    },
    // 预加载第一张图 以便swpier正常push高度
    preFirstImage(e) {
      this.imagesHeight.push(e.mp.detail.height)
    },
    // 预加载第一张图裂开 锁一个默认图和高度
    errorImageFirst(e) {
      const { url, height } = this.defaultImage
      e.mp.target.src = url
      this.imagesHeight.push(height)
    },
  },
}
</script>
<style lang="scss" rel="stylesheet/scss" scoped>
.swiper-container {
  position: relative;
  .indicator-block {
    position: absolute;
    bottom: 20rpx;
    right: 30rpx;
    height: 36rpx;
    line-height: 36rpx;
    border-radius: 19rpx;
    background: rgba(14, 96, 30, 0.6);
  }
}
</style>